import { getMenuList } from "@/api/user";
import router, { resetRouter } from "@/router";

const state = {
  menuList: [],
  token: "",
};

const mutations = {
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList;
  },
  SET_TOKEN(state, token) {
    state.token = token;
  },
};

const actions = {
  getMenuList({ commit }) {
    return new Promise((resolve, reject) => {
      getMenuList()
        .then(({ data }) => {
          if (!data) {
            reject("获取用户菜单列表失败");
          }
          // 存入用户菜单列表
          commit("SET_MENULIST", data);
          resolve(data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  setToken({ commit }, token) {
    commit("SET_TOKEN", token);
  },
  logout({ commit, dispatch }) {
    commit("SET_TOKEN", "");
    commit("SET_MENULIST", []);
    resetRouter();

    dispatch("tagsView/delAllViews", null, { root: true });
  },
  async changeRoles({ commit, dispatch }) {
    // TODO 根据实际情况调整切换角色
    const token = "token";

    commit("SET_TOKEN", token);

    const menus = await dispatch("getMenuList");

    resetRouter();

    const accessRoutes = await dispatch("permission/generateRoutes", menus, {
      root: true,
    });
    router.addRoutes(accessRoutes);

    dispatch("tagsView/delAllViews", null, { root: true });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
